package com.mqb.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class TClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();

        new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            // 会在连接 channel 建立成功后， 触发 active 事件
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) {
                                for (int i = 0; i < 10; i++) {
                                    ByteBuf buf = ctx.alloc().buffer(16);
                                    // buf.writeBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15});
                                    //buf.writeBytes("哈哈哈".getBytes(StandardCharsets.UTF_8));
                                    //ctx.writeAndFlush(buf);
                                    ctx.writeAndFlush(packageMsg("哈哈哈"));
                                }
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
    }

    private static ByteBuf packageMsg(String msg) {
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.heapBuffer(bytes.length + 4);
        System.out.println(byteBuf);
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
        return byteBuf;
    }
}
